<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\WxUser;
use App\Services\Curl;
use App\Services\GetLocation;
use App\Services\PhoneController;
use App\Services\PhoneServer;
use App\Services\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class LoginController extends Controller
{
    private $phoneServer;
    public function __construct(PhoneServer $projectService){
        $this->projectService=$projectService;
    }
    /**
     * @param Request $request
     * @return array
     * 客户端授权登录
     */
    public function login(Request $request)
    {
        //接收参数
        $params = $request->all();
        if (empty($params['code'])) {
            return ['code' => 10004, 'msg' => '请同意授权后进行请求', 'data' => []];
        }
        //微信小程序生成的js_code码
        $js_code = $params['code'];
        //获取微信官方的请求url
        $login_url = sprintf(config('wx.login_url'), $js_code);
        //curl get请求 换取openid和session_key
        $data = Curl::getRequest($login_url);
        //得到openid和session_key
        $openid = $data['openid'];
        $session_key = $data['session_key'];
        //通过openid获取用户信息
        $userInfo = WxUser::getUserInfo($openid);
        //判断是否有该用户信息
        if ($userInfo) {
            //数据库中有该用户信息 则更新用户的头像昵称和session_key
            $user_id = $userInfo->id;
            //组装需要更新的数据
            $updateData = [
                'session_key' => $session_key,
                'nickname' => $params['nickname'],
                'avatar' => $params['avatar']
            ];
            //更新用户信息
            $updateRes = wxUser::updateUserInfo($user_id, $updateData);
            if (!$updateRes) {
                return ['code' => 10004, 'msg' => '登录失败', 'data' => []];
            }
        } else {
            //没有代表用户第一次登录 把用户信息进行入库
            $createData = [
                'nickname' => $params['nickname'],
                'avatar' => $params['avatar'],
                'openid' => $openid,
                'session_key' => $session_key,
            ];
            //添加新用户信息
            $createRes = WxUser::createUser($createData);
            if (!$createRes) {
                return ['code' => 10004, 'msg' => '登录失败', 'data' => []];
            }
            //获取用户id
            $user_id = $createRes->id;
        }
        //通过用户id调用jwt生成token
        $tokenService = new Token();
        $token = $tokenService->crateToken($user_id);
        $userSign = TestController::registerUser('User_' . $user_id);
        //返回token
        return ['code' => 10001, 'msg' => '登录成功', 'data' => ['token' => $token,'userSig'=>$userSign,'userID'=>'User_' . $user_id]];
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 客户端手机号登录
     */
    public function getCode(Request $request)
    {
        //接收用户输入的手机号
        $phone = $request->input('phone');
        //正则验证手机号
        $error = $this->projectService->projectDataValidator($phone);      // 验证表单
        //判断正则手机号是否为空
        if(!empty($error)){
            return $this->failed($error);
        }
        //进行参数验证
        if (empty($phone)) {
            return response()->json(['code' => 1, 'msg' => '手机号不能为空']);
        }
        //从缓存中取出该手机号的验证码记录
        $phoneRes = Cache::get($phone);
        //如果缓存中有记录 则验证码未过期
        if ($phoneRes) {
            return response()->json(['code' => 1, 'msg' => '验证码未过期']);
        }
        //如果没有记录 发送次数+1
        //取出该手机号当天的发送次数
        $num = Cache::get($phone . date('Y-m-d'));
        //判断用户发送次数是否超过限额
        if ($num > 10) {
            return response()->json(['code' => 1, 'msg' => '超过发送限制']);
        }
        //生成验证码
        $code = rand(100000, 999999);
        //将验证码存缓存 有效期为5分钟
        Cache::put($phone, $code, 60);
        $num = $num + 1;
        //记录用户当天的发送次数
        Cache::put($phone . date('Y-m-d'), $num, 24 * 3600);
        return response()->json(['code' => 0, 'msg' => '发送成功', 'data' => $code]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 用户手机号登录
     */
    public function wxLogin(Request $request)
    {
        //接收参数
        $phone = $request->input('phone');
        $code = $request->input('code');
        //从缓存中取出验证码
        $coded = Cache::get($phone);
        //与前端传过来的验证码进行校对
        if ($code != $coded) {
            return response()->json(['code' => 1, 'msg' => '验证码错误']);
        }
        //用户进行登录 或 注册
        $loginRes = WxUser::wxLogin($phone);
        if ($loginRes) {
            //通过用户id 生成 token
            $tokenService = new Token();
            $token = $tokenService->crateToken($loginRes['id']);
            Cache::put($token, $loginRes['id']);
            return response()->json(['code' => 0, 'msg' => '登录成功', 'data' => $token]);
        } else {
            return response()->json(['code' => 1, 'msg' => '登录失败', 'data' => null]);
        }
    }

    /**
     * @param Request $request
     * 获取用户当前位置
     */
    public function getUserLocation(Request $request)
    {
        //接收经纬度
        $params = $request->all();
        if (empty($params['latitude']) || empty($params['longitude'])) {
            response()->json(['code' => 10004, 'msg' => '参数不全', 'data' => null]);
        }
        //纬度
        $latitude = $params['latitude'];
        //经度
        $longitude = $params['longitude'];
        $LocationService = new GetLocation();
        //通过经纬度拼接 获取用户的当前位置
        $location = $latitude . ',' . $longitude;
        $data = $LocationService->getLocation($location);
        //返回用户所在的城市
        return ['adcode' => $data['result']['ad_info']['adcode'], 'city' => $data['result']['ad_info']['city']];
    }


}
